use crate::modules::database::{Database, User, Role};
use crate::modules::interfaces::{UserInterface, CreateUserRequest, UpdateUserRequest, ApiResponse};
use anyhow::Result;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Sha256, Digest};
use time::OffsetDateTime;

#[derive(Debug, Serialize, Deserialize)]
pub struct UserResponse {
    pub id: i32,
    pub username: String,
    pub email: String,
    pub full_name: Option<String>,
    pub phone: Option<String>,
    pub status: String,
    pub last_login: Option<OffsetDateTime>,
    pub roles: Vec<RoleInfo>,
    pub created_at: OffsetDateTime,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RoleInfo {
    pub id: i32,
    pub role_name: String,
    pub description: Option<String>,
}

pub struct UserManagement {
    db: Database,
    config: crate::config::AuthConfig,
}

impl UserManagement {
    pub fn new(db: Database, config: &crate::config::AuthConfig) -> Self {
        println!("使用配置初始化用户管理: {:?}", config);
        Self { 
            db,
            config: config.clone(),
        }
    }

    pub fn create_user(&self, request: CreateUserRequest) -> Result<ApiResponse<UserInterface>> {
        // 检查用户名是否已存在
        if self.db.get_user_by_username(&request.username).is_some() {
            return Err(anyhow::anyhow!("用户名已存在"));
        }

        let password_hash = Self::hash_password(&request.password)?;
        let now = OffsetDateTime::now_utc();
        
        let user = User {
            id: 0, // 数据库会自动生成
            username: request.username,
            email: request.email,
            password_hash,
            full_name: request.full_name,
            phone: request.phone,
            status: "active".to_string(),
            last_login: None,
            created_at: now,
            updated_at: now,
            created_by: Some(1), // 系统创建
        };

        let user_id = self.db.add_user(user);
        
        // 获取用户信息并转换为接口类型
        let user = self.db.get_user(user_id).ok_or(anyhow::anyhow!("用户创建失败"))?;
        let user_interface = self.convert_to_user_interface(user)?;
        
        Ok(ApiResponse::success(user_interface))
    }

    pub fn get_user_by_id(&self, user_id: i32) -> Result<ApiResponse<UserInterface>> {
        let user = self.db.get_user(user_id).ok_or(anyhow::anyhow!("用户不存在"))?;
        let user_interface = self.convert_to_user_interface(user)?;
        Ok(ApiResponse::success(user_interface))
    }

    pub fn get_user_by_username(&self, username: &str) -> Result<ApiResponse<Option<UserInterface>>> {
        if let Some(user) = self.db.get_user_by_username(username) {
            let user_interface = self.convert_to_user_interface(user)?;
            Ok(ApiResponse::success(Some(user_interface)))
        } else {
            Ok(ApiResponse::success(None))
        }
    }

    pub fn update_user(&self, user_id: i32, request: UpdateUserRequest) -> Result<ApiResponse<UserInterface>> {
        let mut user = self.db.get_user(user_id).ok_or(anyhow::anyhow!("用户不存在"))?;
        let now = OffsetDateTime::now_utc();

        // 更新用户基本信息
        if let Some(email) = request.email {
            user.email = email;
        }

        if let Some(full_name) = request.full_name {
            user.full_name = Some(full_name);
        }

        if let Some(phone) = request.phone {
            user.phone = Some(phone);
        }

        if let Some(status) = request.status {
            user.status = status;
        }

        user.updated_at = now;

        if !self.db.update_user(user_id, user) {
            return Err(anyhow::anyhow!("用户更新失败"));
        }

        self.get_user_by_id(user_id)
    }

    pub fn delete_user(&self, user_id: i32) -> Result<ApiResponse<bool>> {
        let result = self.db.delete_user(user_id);
        Ok(ApiResponse::success(result))
    }

    pub fn list_users(&self, page: i32, page_size: i32) -> Result<ApiResponse<Vec<UserInterface>>> {
        let all_users = self.db.get_all_users();
        let offset = ((page - 1) * page_size) as usize;
        let limit = page_size as usize;
        
        let users = if offset >= all_users.len() {
            Vec::new()
        } else {
            let end = std::cmp::min(offset + limit, all_users.len());
            all_users[offset..end].to_vec()
        };

        let mut user_interfaces = Vec::new();
        
        for user in users {
            let user_interface = self.convert_to_user_interface(user)?;
            user_interfaces.push(user_interface);
        }

        Ok(ApiResponse::success(user_interfaces))
    }

    pub fn authenticate_user(&self, username: &str, password: &str) -> Result<ApiResponse<UserInterface>> {
        if let Some(db_user) = self.db.get_user_by_username(username) {
            // 直接验证数据库中的密码哈希
            if self.verify_password_with_hash(password, &db_user.password_hash)? {
                // 更新最后登录时间
                let mut user_to_update = db_user.clone();
                user_to_update.last_login = Some(OffsetDateTime::now_utc());
                self.db.update_user(user_to_update.id, user_to_update);
                
                // 返回用户接口
                let user_interface = self.convert_to_user_interface(db_user)?;
                Ok(ApiResponse::success(user_interface))
            } else {
                Err(anyhow::anyhow!("用户名或密码错误"))
            }
        } else {
            Err(anyhow::anyhow!("用户不存在"))
        }
    }

    fn convert_to_user_interface(&self, user: User) -> Result<UserInterface> {
        Ok(UserInterface {
            id: user.id,
            username: user.username,
            email: user.email,
            full_name: user.full_name,
            phone: user.phone,
            status: user.status,
            last_login: user.last_login,
            created_at: user.created_at,
        })
    }

    fn hash_password(password: &str) -> Result<String> {
        let mut salt = [0u8; 16];
        rand::thread_rng().fill_bytes(&mut salt);
        
        let mut hasher = Sha256::new();
        hasher.update(&salt);
        hasher.update(password.as_bytes());
        let hash = hasher.finalize();
        
        let mut result = String::new();
        result.push_str(&hex::encode(salt));
        result.push(':');
        result.push_str(&hex::encode(hash));
        Ok(result)
    }

    fn verify_password_with_hash(&self, password: &str, password_hash: &str) -> Result<bool> {
        // 解析密码哈希（格式：salt:hash）
        let parts: Vec<&str> = password_hash.split(':').collect();
        if parts.len() != 2 {
            return Ok(false);
        }
        
        let salt = hex::decode(parts[0]).map_err(|e| anyhow::anyhow!("密码哈希格式错误: {}", e))?;
        let stored_hash = hex::decode(parts[1]).map_err(|e| anyhow::anyhow!("密码哈希格式错误: {}", e))?;
        
        // 计算输入密码的哈希
        let mut hasher = Sha256::new();
        hasher.update(&salt);
        hasher.update(password.as_bytes());
        let computed_hash = hasher.finalize();
        
        // 比较哈希值
        Ok(computed_hash.as_slice() == stored_hash.as_slice())
    }
}